global.FS = require('fs');
global.PATH = require("path"); 
global.ZLIB = require('zlib');
global.MYSQL  = require('mysql');
global.CAPTCHA = require('svg-captcha');
global.http = require('http');
global.https = require('https');
global.url = require('url');
global.multiparty = require('multiparty');
global.REQ = require('request');
global.CRYPTO = require('crypto');
global.DB = MYSQL.createPool(MYSQLconfig);
global.WebSocket = require('ws');
var MSGPACK = require("msgpack-lite");
var DGRAM = require('dgram');
var UDPSERVER = DGRAM.createSocket('udp4');
DB.on('error', function(err) {
    console.log(err);
});
process.on("uncatchException", function(e) {
    console.log(e);
});
/*强行环境处理 */
const argv = process.argv;
let batcmd = argv['3']?argv['3']:argv['2'];
if(batcmd && batcmd.length > 2 && batcmd.indexOf('@@') == -1){
    batcmd = batcmd.replace(/\.\./g,'');
    if(batcmd.length > 2){
        Http = batcmd;
    }
}
global.BIANHAO = argv['3']?argv['3']:argv['2'];
if(Http == "tencent" ||  Http == "aliyun"){
    global.temp  = '/tmp/';
    global.Debug  = false;
}
/*模版文件缓存 */
/*禁止浏览器直接访问名单小写*/
global.BLACK = {
    'tools':'tools',
    'mysql':'mysql',
    'tpl':'tpl'
};
global.strtolower = (data)=>{
    if(!data){
        return "";
    }
    return data.toLowerCase();
}
global.json_encode = (data)=>{
    if(!data){
        return `{}`;
    }
    try {
        return JSON.stringify(data);
    } catch (error) {
        return `{}`;
    }
    
}
global.JSON_DECODE = (data)=>{
    if(!data){
        return false;
    }
    try {
        return JSON.parse(data);
    } catch (error) {
        return false;
    }
}

global.Urlcurl = function(url){
    url = encodeURIComponent(url);
    url = url.replace(/\%3A/g, ":");
    url = url.replace(/\%2F/g, "/");
    url = url.replace(/\%3F/g, "?");
    url = url.replace(/\%3D/g, "=");
    url = url.replace(/\%26/g, "&");
    return url;
}

global.json_decode = (data)=>{
 
    if(!data){
        return {};
    }
    try {
        return JSON.parse(data);
    } catch (error) {
        return {};
    }
}
global.is_array =  (k)=>{
    if(!k){
        return false;
    }
    if(typeof(k) =="string" ){
        return false;
    }
    return true;
}

global.implode =  (k,v)=>{
    let vvv = [];
    if(!v){
        return "";
    }
    if(v){
        for(let i  in v){
            vvv.push(v[i]);
        }
    }
    return vvv.join(k);
}

global.explode =  (k,v)=>{
    return v.split(k);
}

global.XmlJx =  (xml)=>{
    var obj = {}, R1 = /<(\w+)>([\s\S]*)<\/\1>/ig,R2=/<(\w+)>([\s\S]*)<\/\1>/i, R3 = /<\!\[CDATA\[([\s\S]*)\]\]>/i;
    while(R1.exec(xml)){
        var k = RegExp.$1, v = RegExp.$2;
        obj[k] = R2.test(v) ? XmlJx(v) : (R3.test(v) ? RegExp.$1 : v)
    }
    return obj;
}

global.str_replace = (k,v,value)=>{
    if(!v){
        v = "";
    }
    if(typeof(k) == "string"){
        return value.replace(new RegExp(k,"igm"),v);
    }
    let tempx =  ""+value;
    for(var m in k){
        let z = k[m];
        let vm = v[m];
        if(!vm){
            vm = "";
        }
        tempx = tempx.replace(new RegExp(z,"igm"),vm);
    }
    return tempx;
}

global.strtoupper = (data)=>{
    if(!data){
        return "";
    }
    return data.toUpperCase();
}

global.strpos = (k,v)=>{
    if(!k ||  k.indexOf(v) <= -1){
        return false;
    }
    return true;
}

global.platform = ($anget)=>{
    $anget = Trim($anget);
    if ($anget == "") {
        return "未知";
    }
    let $xitong = "";
    let $hj = " web";
    let $shuju = null;
    let $xotp = null;
    let $system = null;
    $shuju =  explode(')', $anget);
    if ($shuju) {
        $xotp = explode('(', $shuju['0']);
    }
    if ($xotp && isset($xotp['1'])) {
        $system = explode(';', $xotp['1']);
    }
    if (strpos($anget, "ISAPP") !== false) {
        $hj = "APP";
    }else if (strpos($anget, "ISWX") !== false) {
        $hj = "WX";
    }
    if (strpos(strtolower($anget), "android") !== false) {
        $xitong = "Android ";
    } else if (strpos($anget, "iOS") !== false) {
        $xitong = "iOS ";
    } else {
        if ($system && count($system) > 1) {
            $xitong = $system['1'];
        } else {
            $xitong = "其他 ";
        }
    }
    let $sj = "";
    if ($system && isset($system['2'])) {
        $sj = " " + $system['2'];
    }
    return  $xitong + $hj + $sj;
}

global.jiaqian = async ($uid , $type ,   $money , $integral , $currency , $data , $ip , $plugin , $sql,biaohao,fanhuix  )=>{
    if(!$uid) $uid = 0;
    if(!$type) $type = 0;
    if(!$money)$money = 0;
    if(!$integral)$integral = 0;
    if(!$currency)$currency = 0;
    if(!$data)$data = "";
    if(!$ip)$ip  = "";
    if(!$plugin)$plugin  = "";
    if(!$sql)$sql  = "";
    if(!biaohao)biaohao  =0;
    if(!fanhuix){
        fanhuix = false;
    }
    $money = Mode("Tools").FJine($money)*1;
    $currency = Mode("Tools").FJine($currency)*1;
    $integral = Mode("Tools").Int($integral)*1;
    if($uid < 0)return false;
    let $D = await db("user");
    let YUAN = await $D.ZhiCha("money,integral,currency").Where({'id':$uid}).Find();
    if(!YUAN){return false;}
    $D = await $D.SetShiwu(true);
    let $where  ={};

    if ($money  != 0) {
        $where = {'id':$uid};
        if ($money < 0) {
            $where['money >='] = -$money;
        }
        $D = await $D.SetTable('user');
     
        $sql += await $D.Where($where).Update({'money +':$money});
        $D = await $D.SetTable('moneylog');
        $sql += await $D.Insert({
            'uid' : $uid,
            'type' : $type,
            'rawnum':YUAN['money'],
            'num' : $money,
            'nownum' : YUAN['money'] + $money,
            'pluginid' : $plugin,
            'data' : $data,
            'ip' : $ip,
            'off':biaohao,
            'atime': Mode("Tools").Time()
        });
    }
    
    if ($integral  != 0) {
        $where = {'id':$uid};
        if ($integral < 0) {
            $where['integral >='] = -$integral;
        }
        $D = await $D.SetTable('user');
        $sql += await $D.Where($where).Update({'integral +':$integral});
        $D = await $D.SetTable('integrallog');
        $sql += await $D.Insert({
            'uid' : $uid,
            'type' : $type,
            'rawnum':YUAN['integral'],
            'num' : $integral,
            'nownum' : YUAN['integral'] +$integral,
            'pluginid' : $plugin,
            'data' : $data,
            'ip' : $ip,
            'off':biaohao,
            'atime': Mode("Tools").Time()
        });
    }

    if ($currency  != 0) {
        $where = {'id':$uid};
        if ($currency < 0) {
            $where['currency >='] = -$currency;
        }
        $D = await $D.SetTable('user');
        $sql += await $D.Where($where).Update({'currency +':$currency});
        $D = await $D.SetTable('currencylog');
        $sql += await $D.Insert({
            'uid' : $uid,
            'type' : $type,
            'rawnum':YUAN['currency'],
            'num' : $currency,
            'nownum':YUAN['currency']+$currency,
            'pluginid' : $plugin,
            'data' : $data,
            'ip' : $ip,
            'off':biaohao,
            'atime': Mode("Tools").Time()
        });
    }
    if(fanhuix){
        return $sql;
    }
    if($sql == ""){
        return false;
    }
    let $fan = await $D.ShiWu($sql);
    if ($fan) {
        return await Uid($uid, 1);
    } else return false;
}



global.strtotime = (timex)=>{
    return Date.parse(new Date(timex))/1000;
}

global.isset = (pic)=>{
    if(pic === 0){
        return true;
    }
    if( typeof(pic) == "undefined"){
        return false;
    }
    return true;
}
global.strlen = (name)=>{
    if(!name){
        return false;
    }
    return name.length;
}

global.pichttp = (pic)=>{
    if(!pic || pic ==""){
        return CDNHOST+'Tpl/noimg.png';
    }else if(pic.indexOf("#LINK#") > -1){
       let jiexi = explode('#LINK#',pic);
       if(jiexi[0].indexOf("://") > -1){
            return pic;
        }else{
            return CDNHOST+LTrim(pic,'/');
        }
    }else if(pic.indexOf("://") > -1){
        return pic;
    }else{
        return CDNHOST+LTrim(pic,'/');
    }
}

global.Md5 = (content)=>{
    return CRYPTO.createHash('md5').update(Buffer.from(content, 'utf8')).digest('hex');
}

global.Kuomm = ($var)=>{
    if(!$var){
        $var = ADMINSafety;
    }
    let base64 = Buffer.from($var+'知者不惑，').toString('base64');
    let sha1 = CRYPTO.createHash('sha1').update(Buffer.from($var+ '勇者不惧，', 'utf8')).digest('hex');
    var $varstr = $var.length;
    if ($varstr < 1) {
        $varstr = 32;
    }
    let $hash = CRYPTO.createHash('md5').update(Buffer.from('@中国@'+base64+$var+'仁者不忧，'+sha1+'@制造@', 'utf8')).digest('hex');
    return $hash.substr(1,$varstr * 3);
}


global._POST_ =(post,k,v)=>{
    if(!k || k == ""){
        return false;
    }
    if (k.indexOf("[") >-1 ) {
        delete post[k];
        k = k.replace(/\[/g,'{@@}').replace(/\]/g,'');
        var klist = k.split('{@@}');
        var chang = klist.length  - 1;
        for (let i = 0; i < chang; i++) {
            if (!post[klist[i]]) post[klist[i]] = {};
            post = post[klist[i]];
        }
        post[klist[chang]] = v;
    }
}

global.MODE = (source,onec)=>{
    if(onec){
        if(!source.MODENAME){
            source._____MODE_NAME = "KUO"+('xxyxxxxyxxxyxxyxxxxyxxxxyxxxxxxyxx'.replace(/[xy]/g, function(c) {
                var r = Math.random()*36|0, v = c == 'x' ? r : (r&0x3|0x8);
                return v.toString(36);
            }));
        }
        if(!global['COPY_'+source._____MODE_NAME]){
            global['COPY_'+source._____MODE_NAME] = Object.assign({}, source);
        }
        return global['COPY_'+source._____MODE_NAME];
    }else{
        return Object.assign({}, source);
    }
}
/* 核心函数 跨插件调用数据 */
global.Mode =  (name,config) =>{
    if(!global['Kuo_'+name]){
        try {
            global['Kuo_'+name] = require(Controller+'Kuo_'+name+'.js');
        } catch (ee) {
            if(Debug)console.log(ee);
            global['Kuo_'+name] = {};
        }
    }
    if(config && global['Kuo_'+name].Config){
        if(!global['Kuo_'+name].ConfigLoad){
            global['Kuo_'+name].Config(config);
            global['Kuo_'+name].ConfigLoad = true;
        }
    }
   
    return global['Kuo_'+name];
}

//创建目录
global.MkDirs = (dirname) =>{
    if (FS.existsSync(dirname)) {
        return true;
    } else {
        if (MkDirs(PATH.dirname(dirname))) {
            FS.mkdirSync(dirname);
            return true;
        }
    }
}
//删除目录
global.DelDirs = (path) =>{
    let files = [];
    if(FS.existsSync(path)){
        files = FS.readdirSync(path);
        files.forEach((file, index) => {
            let curPath = path + "/" + file;
            if(FS.statSync(curPath).isDirectory()){
                DelDirs(curPath); //递归删除文件夹
            } else {
                FS.unlinkSync(curPath); //删除文件
            }
        });
        FS.rmdirSync(path);  // 删除文件夹自身
    }
}

//左删除字符
global.LTrim = function(str,zifu) {
    if(typeof(str) =="undefined" || !str){
        return str;
    }
    if(str == ""){
        return "";
    }
    if(typeof(zifu) =="undefined"){
        zifu = ' ';
    }
    if(str.indexOf(zifu) <= -1){
        return str;
    }
    var qie = str.split(zifu);
    if(qie['0'] != ""){
        return str;
    }

    qie.shift();
    return qie.join(zifu);
};
//右删除字符
global.RTrim = function(str,zifu) {
    if(typeof(str) =="undefined" || !str){
        return str;
    }
    if(str == ""){
        return "";
     }
    if(typeof(zifu) =="undefined"){
        zifu = ' ';
    }
    if(str.indexOf(zifu) <= -1){
        return str;
    }

    var qie = str.split(zifu);
    if(qie[qie.length-1] != ""){
        return str;
    }
    qie.pop();
    return qie.join(zifu);
};
//删除字符
global.Trim = function(str,zifu) {
    if(!zifu){
      zifu = ",";
    }
    return LTrim(RTrim(str,zifu),zifu);
};
// 数据库申明
global.db = async (name) =>{
    var shuju = Mode("Mysql")();
    await shuju.Init(name);
    return shuju;
}
global.GET = async (link,canshu) =>{
    return new Promise((resolve, reject) => {
        var CANSHU = {
            method: 'GET',
            gzip: true,
            url:Urlcurl(link)
        };
        if(canshu){
            for(var i in canshu){
                CANSHU[i] = canshu[i];
            }
        }
        REQ(CANSHU, function optionalCallback(err, res, body) {
            if(err){
                if(Debug){
                    p(err);
                }
                resolve(false);
                return false;
            }
            if(res && res.statusCode){
                
                if(res.statusCode != 500){
                    resolve(body);
                    return true;
                }else if(Debug){
                    p(body);
                }
                
                resolve(false);
                return false;
            }
        });
    });
}
global.POST = async (link,shuju,canshu) =>{
    return new Promise((resolve, reject) => {
        var CANSHU = {
            method: 'post',
            gzip: true,
            url:Urlcurl(link),
            formData:shuju
        };
        if(canshu){
            for(var i in canshu){
                CANSHU[i] = canshu[i];
            }
        }
        REQ(CANSHU, function optionalCallback(err, res, body) {
            if(err){
                if(Debug){
                    p(err);
                }
                resolve(false);
                return false;
            }
            if(res && res.statusCode){
                if(res.statusCode != 500){
                    resolve(body);
                    return true;
                }else if(Debug){
                    p(body);
                }
                resolve(false);
                return false;
            }
        });
    });
}
global.Kuolog = async ($baio, $id , $type , $data , $mode , $plugin , $ip )=>{
    if(!$baio) $baio = "adminlog";
    if(!$id)$id =0;
    if(!$type)$type =0;
    if(!$data)$data ="";
    if(!$mode) $mode ="";
    if(!$plugin) $plugin ="";
    if(!$ip)$ip ="";
    let $db = await db($baio);
    return await $db.Insert({
        uid:Number($id),
        type:Number($type),
        data:typeof($data)=="string"?$data:JSON.stringify($data),
        controller:$plugin,
        mode:$mode,
        atime:Mode("Tools").Time(),
        ip:$ip
    });
}

global.KuoLink = ($plush,$PAGE)=>{
    if(!$PAGE){
        $PAGE = 1;
    }
    if (!$plush) {
        return WZHOST ;
    }
    if (Defaultplus != '' && $plush['0'] == Defaultclass) {
        delete($plush['0']);
    }else if (Defaultplus != ''){
        if($plush['0'] != Defaultplus){
            $plush.unshift(Defaultplus);
        }
    }
    let  $houzui = WebExt;
    if($PAGE >  1){
        $plush.push("");
        $houzui = "";
    }
    return WZHOST + implode(FENGE, $plush) + $houzui;
}
global.KuoSecurity = ($name)=>{
    return str_replace(['-', '#', '/', '，', '|', '、', '\\\\', '\\*', '\\?', '<', '>', '.', "\n", "\r", '【', '】', '\\(', '\\)', '：', '\\{', '\\}', '\'', '"', '\:', ';', ' '], ['_', ''], strtolower(Trim($name)));
}

global.reset =($data)=>{
    if(!$data){
        return "";
    }
    if($data[0]){
        return $data[0];
    }
    for(var xx in $data){
        return $data[xx];
    }
    return "";
}

global.count =($name)=>{
    if(typeof($name.length) == "undefined"){
        return Object.keys($name).length;
    }else{
        return $name.length;
    }
}

global.Kuoconfig =async ($name, $qx)=>{
    if(!$qx){
        $qx = 0;
    }
    let $hash = 'config/'+ Md5($name);
    if ($qx == 2) {
        Mem.Del($hash);
        return false;
    }
    let $data = await Mem.Get($hash);
    if($data == -1 && $qx == 0){
        return false;
    }else if ($data && $qx ==0) {
        return $data;
    }
    let $db = await db('config');
    let $dbc = await $db.Where({pluginid : $name}).Find();
    if(!$dbc ){
        Mem.Set($hash,-1,10);
        return false;
    }
    if ($dbc) {
        if ($dbc['data'] != '') {
            let $DATA = explode(',', $dbc['data']);
            if (count($DATA) == 1) {
                $DATA = reset($DATA);
            }
            Mem.Set($hash, $DATA);
            return $DATA;
        }
        return "";
    }
}
global.Kuoplus =async ($name, $qx)=>{
    if(!$qx){
        $qx = 0;
    }
    let $hash = 'plus/'+ Md5($name);
    if ($qx == 2) {
        Mem.Del($hash);
        return false;
    }
    let $data = await Mem.Get($hash);
    if($data == -1 && $qx == 0){
        return false;
    }else if ($data && $qx ==0) {
        return $data;
    }
    let $db = await db('features');
    let $dbc = await $db.Where({pluginid : $name}).Find();
    if(!$dbc ){
        Mem.Set($hash,-1,10);
        return false;
    }
    if ($dbc['configure'] != "") {
        $dbc['configure']  = JSON.parse($dbc['configure']);
    } else {
        $dbc['configure'] = {};
    }
    if ($dbc['menuconfig'] != "") {
        $dbc['menuconfig']  = JSON.parse($dbc['menuconfig']);
    }else {
        $dbc['menuconfig'] = {};
    }
    Mem.Set($hash,$dbc);
    return $dbc;
}
global.Uid = async ($uid, $qx)=>{
    $uid = Number($uid);
    if ($uid < 1) {
        return false;
    }
    if(!$qx){
        $qx = 0;
    }
    let $hash = 'uid/'+ $uid;
    if ($qx == 2) {
        await Mem.Del($hash);
        return false;
    }
    let $data = await Mem.Get($hash);
    if ($data == -1 && $qx == 0) {
        return false;
    }
    if ($data && $qx == 0) {
        return $data;
    }
    let $db = await db('user')
    let DATA = await $db.Where({id:$uid}).Find();
    if(DATA){
        await Mem.Set($hash,DATA);
        return DATA;
    }
    await Mem.Set($hash,-1,10);
    return false;
}
global.Adminid = async ($uid, $qx)=>{
    $uid = Number($uid);
    if ($uid < 1) {
        return false;
    }
    if(!$qx){
        $qx = 0;
    }
    let $hash = 'adminid/'+ $uid;
    if ($qx == 2) {
        Mem.Del($hash);
        return false;
    }
    let $data = await Mem.Get($hash);
    if ($data == -1 && $qx == 0) {
        return false;
    }
    if ($data && $qx == 0) {
        return $data;
    }
    let $db = await db('admin')
    let DATA = await $db.Where({id:$uid}).Find();
    if(DATA){
        Mem.Set($hash,DATA);
        return DATA;
    }
    Mem.Set($hash,-1,10);
    return false;
}

global.getarray=function(signArgs,bianma){
    let zuhe = [];
    for(var key in signArgs){
        let value = signArgs[key];
        if(bianma){
            value = encodeURIComponent(value);
        }
        zuhe.push(`${key}=${value}`);
    }
    return zuhe.join("&");
}

global.azpaixu=function(signArgs){
    let paixu = Object.keys(signArgs).sort().filter(val => val);
    let newx = {};
    for(var k in paixu){
        let tzhi = paixu[k];
        newx[tzhi] = signArgs[tzhi];
    }
    return newx;
}

global.formatKey =(key, type) =>{
    const item = key.split('\n').map(val => val.trim());
    if (item[0].includes(type)) {
        item.shift();
    }
    if (item[item.length - 1].includes(type)) {
        item.pop();
    }
    return `-----BEGIN ${type}-----\n${item.join('')}\n-----END ${type}-----`;
}
//PKCS1(非JAVA适用)
global.SHA256_verify = function($content, $sign, $publicKey){   
    $publicKey = formatKey($publicKey, "PUBLIC KEY");
    let verify = CRYPTO.createVerify('RSA-SHA256');
    verify.update($content);
    return verify.verify($publicKey, $sign , 'base64');
}
//PKCS1(非JAVA适用)
global.SHA256_sign = function($content,$publicKey){
    $publicKey = formatKey($publicKey, "PRIVATE KEY");
    let sign = CRYPTO.createSign('RSA-SHA256');
    sign.update($content, 'utf-8');
    return sign.sign($publicKey, 'base64');
}

global.orderid=function(biao){
    if(!biao){
        biao = "kuo";
    }
   return biao+Mode("Tools").Time()+ Math.floor(Math.random()*1000000)+SJ(100,999);
}

global.SJ=function(min,max){
    if(!max) max =10;
    if(!min)min =1;
    return Math.floor(Math.random()*(max-min+1)+min);
}
global.VCODE = async(id)=>{
    var qian = SJ(10,90);
    var hou  = SJ(1,10);
    var x = ['+','-','*'];
    var fu = x[SJ(1,3)-1];
    var sji = SJ(1,9);
    var stringx = qian+fu+hou+'+'+sji;
    CAPTCHA.loadFont(dir+'config/1.ttf');
    var captcha = CAPTCHA(stringx+" =",{ noise: 4, size:6});
    var zhi = 0;
    if(fu == '+'){
        zhi = qian+hou+sji;
    }else  if(fu == '-'){
        zhi = qian-hou+sji;
    }else if(fu == '*'){
        zhi = qian*hou+sji;
    }
    await Mem.Put("session/"+id,{code: parseInt(zhi) },Expiredseconds);
    return captcha;
}
//直接缓存表结构
if(Http == "http"){
    Mode("Mysql")().TableList();
    MkDirs(temp);
}
global.Mem = Mode("Cache_"+MemClass,MemClassConfig);
/* 数据库 ok */
/* kv 缓存系统 ok */
/* get  ok */
/* post ok */
/* 验证码 ok*/
/* 文件上传处理 "wotian",kuo.files */
global.Upload = async (biao,files,tmp_name_)=>{
    if(!biao ){
        biao =  "all";
    }
    var chulilist = [];
    var msg = "";
    if(files){
        for(var i in files ){
            var douge = files[i];
            var NAME = douge.name;
            var ext = douge.tmp_name.split(".");
            var houzui = ext.pop();
            NAME = str_replace("."+houzui,'',NAME);
            var ext_ = houzui.toLowerCase();
            if(douge.field != biao || douge.size > UPconfig.size || ! UPconfig.ext.includes(ext_)){
                if(douge.field != biao){
                    msg+=" file not ";
                }
                if(douge.size > UPconfig.size){
                    msg+=" size error ";
                }
                if(! UPconfig.ext.includes(ext_) ){
                    msg+=" ext error ";
                }
                try {
                    FS.unlinkSync(douge.tmp_name);
                } catch (error) {}

            }else{
                var fTime = new Date();
                if(!tmp_name_){

                    if(typeof(UPconfig.name) != 'undefined' && UPconfig.name != "" && NAME != ""){
                        tmp_name_ = "/attachment/"+fTime.getFullYear().toString()+"-"+(fTime.getMonth()+1).toString()+"/"+ext_+"/"+Mode("Tools").Xss(Mode("Tools").GUoLV(NAME))+Mode("Tools").Date(Mode("Tools").GUoLV(UPconfig.name))+"."+ext_;
                    }else{
                        tmp_name_ = "/attachment/"+fTime.getFullYear().toString()+"-"+(fTime.getMonth()+1).toString()+"/"+ext_+"/"+Md5(douge.tmp_name)+"."+ext_;
                    }
                }
                var fan = await Mode("UP_"+UPClass,UPconfig).Upload(douge.tmp_name,tmp_name_);
                if(fan){
                    chulilist.push(tmp_name_);
                }
                try {
                    FS.unlinkSync(douge.tmp_name);
                } catch (error) {}
            }
        }
    }
    if(chulilist.length < 1){
        return {code:0, msg:msg};
    }
    return {code:1,content:{pic:chulilist.join(","),size:douge.size,houzui:ext_}};
}

global.Mime = {"*":"application\/octet-stream","tif":"application\/x-tif","001":"application\/x-001","301":"application\/x-301","323":"text\/h323","906":"application\/x-906","907":"drawing\/907","a11":"application\/x-a11","acp":"audio\/x-mei-aac","ai":"application\/postscript","aif":"audio\/aiff","aifc":"audio\/aiff","aiff":"audio\/aiff","anv":"application\/x-anv","asa":"text\/asa","asf":"video\/x-ms-asf","asp":"text\/asp","asx":"video\/x-ms-asf","au":"audio\/basic","avi":"video\/avi","awf":"application\/vnd.adobe.workflow","biz":"text\/xml","bmp":"application\/x-bmp","bot":"application\/x-bot","c4t":"application\/x-c4t","c90":"application\/x-c90","cal":"application\/x-cals","cat":"application\/vnd.ms-pki.seccat","cdf":"application\/x-netcdf","cdr":"application\/x-cdr","cel":"application\/x-cel","cer":"application\/x-x509-ca-cert","cg4":"application\/x-g4","cgm":"application\/x-cgm","cit":"application\/x-cit","class":"java\/*","cml":"text\/xml","cmp":"application\/x-cmp","cmx":"application\/x-cmx","cot":"application\/x-cot","crl":"application\/pkix-crl","crt":"application\/x-x509-ca-cert","csi":"application\/x-csi","css":"text\/css","cut":"application\/x-cut","dbf":"application\/x-dbf","dbm":"application\/x-dbm","dbx":"application\/x-dbx","dcd":"text\/xml","dcx":"application\/x-dcx","der":"application\/x-x509-ca-cert","dgn":"application\/x-dgn","dib":"application\/x-dib","dll":"application\/x-msdownload","doc":"application\/msword","dot":"application\/msword","drw":"application\/x-drw","dtd":"text\/xml","dwf":"application\/x-dwf","dwg":"application\/x-dwg","dxb":"application\/x-dxb","dxf":"application\/x-dxf","edn":"application\/vnd.adobe.edn","emf":"application\/x-emf","eml":"message\/rfc822","ent":"text\/xml","epi":"application\/x-epi","eps":"application\/postscript","etd":"application\/x-ebx","exe":"application\/x-msdownload","fax":"image\/fax","fdf":"application\/vnd.fdf","fif":"application\/fractals","fo":"text\/xml","frm":"application\/x-frm","g4":"application\/x-g4","gbr":"application\/x-gbr","":"application\/x-","gif":"image\/gif","gl2":"application\/x-gl2","gp4":"application\/x-gp4","hgl":"application\/x-hgl","hmr":"application\/x-hmr","hpg":"application\/x-hpgl","hpl":"application\/x-hpl","hqx":"application\/mac-binhex40","hrf":"application\/x-hrf","hta":"application\/hta","htc":"text\/x-component","htm":"text\/html","html":"text\/html","htt":"text\/webviewhtml","htx":"text\/html","icb":"application\/x-icb","ico":"application\/x-ico","iff":"application\/x-iff","ig4":"application\/x-g4","igs":"application\/x-igs","iii":"application\/x-iphone","img":"application\/x-img","ins":"application\/x-internet-signup","isp":"application\/x-internet-signup","IVF":"video\/x-ivf","java":"java\/*","jfif":"image\/jpeg","jpe":"application\/x-jpe","jpeg":"image\/jpeg","jpg":"application\/x-jpg","js":"application\/x-javascript","jsp":"text\/html","la1":"audio\/x-liquid-file","lar":"application\/x-laplayer-reg","latex":"application\/x-latex","lavs":"audio\/x-liquid-secure","lbm":"application\/x-lbm","lmsff":"audio\/x-la-lms","ls":"application\/x-javascript","ltr":"application\/x-ltr","m1v":"video\/x-mpeg","m2v":"video\/x-mpeg","m3u":"audio\/mpegurl","m4e":"video\/mpeg4","mac":"application\/x-mac","man":"application\/x-troff-man","math":"text\/xml","mdb":"application\/x-mdb","mfp":"application\/x-shockwave-flash","mht":"message\/rfc822","mhtml":"message\/rfc822","mi":"application\/x-mi","mid":"audio\/mid","midi":"audio\/mid","mil":"application\/x-mil","mml":"text\/xml","mnd":"audio\/x-musicnet-download","mns":"audio\/x-musicnet-stream","mocha":"application\/x-javascript","movie":"video\/x-sgi-movie","mp1":"audio\/mp1","mp2":"audio\/mp2","mp2v":"video\/mpeg","mp3":"audio\/mp3","mp4":"video\/mpeg4","mpa":"video\/x-mpg","mpd":"application\/vnd.ms-project","mpe":"video\/x-mpeg","mpeg":"video\/mpg","mpg":"video\/mpg","mpga":"audio\/rn-mpeg","mpp":"application\/vnd.ms-project","mps":"video\/x-mpeg","mpt":"application\/vnd.ms-project","mpv":"video\/mpg","mpv2":"video\/mpeg","mpw":"application\/vnd.ms-project","mpx":"application\/vnd.ms-project","mtx":"text\/xml","mxp":"application\/x-mmxp","net":"image\/pnetvue","nrf":"application\/x-nrf","nws":"message\/rfc822","odc":"text\/x-ms-odc","out":"application\/x-out","p10":"application\/pkcs10","p12":"application\/x-pkcs12","p7b":"application\/x-pkcs7-certificates","p7c":"application\/pkcs7-mime","p7m":"application\/pkcs7-mime","p7r":"application\/x-pkcs7-certreqresp","p7s":"application\/pkcs7-signature","pc5":"application\/x-pc5","pci":"application\/x-pci","pcl":"application\/x-pcl","pcx":"application\/x-pcx","pdf":"application\/pdf","pdx":"application\/vnd.adobe.pdx","pfx":"application\/x-pkcs12","pgl":"application\/x-pgl","pic":"application\/x-pic","pko":"application\/vnd.ms-pki.pko","pl":"application\/x-perl","plg":"text\/html","pls":"audio\/scpls","plt":"application\/x-plt","png":"application\/x-png","pot":"application\/vnd.ms-powerpoint","ppa":"application\/vnd.ms-powerpoint","ppm":"application\/x-ppm","pps":"application\/vnd.ms-powerpoint","ppt":"application\/x-ppt","pr":"application\/x-pr","prf":"application\/pics-rules","prn":"application\/x-prn","prt":"application\/x-prt","ps":"application\/postscript","ptn":"application\/x-ptn","pwz":"application\/vnd.ms-powerpoint","r3t":"text\/vnd.rn-realtext3d","ra":"audio\/vnd.rn-realaudio","ram":"audio\/x-pn-realaudio","ras":"application\/x-ras","rat":"application\/rat-file","rdf":"text\/xml","rec":"application\/vnd.rn-recording","red":"application\/x-red","rgb":"application\/x-rgb","rjs":"application\/vnd.rn-realsystem-rjs","rjt":"application\/vnd.rn-realsystem-rjt","rlc":"application\/x-rlc","rle":"application\/x-rle","rm":"application\/vnd.rn-realmedia","rmf":"application\/vnd.adobe.rmf","rmi":"audio\/mid","rmj":"application\/vnd.rn-realsystem-rmj","rmm":"audio\/x-pn-realaudio","rmp":"application\/vnd.rn-rn_music_package","rms":"application\/vnd.rn-realmedia-secure","rmvb":"application\/vnd.rn-realmedia-vbr","rmx":"application\/vnd.rn-realsystem-rmx","rnx":"application\/vnd.rn-realplayer","rp":"image\/vnd.rn-realpix","rpm":"audio\/x-pn-realaudio-plugin","rsml":"application\/vnd.rn-rsml","rt":"text\/vnd.rn-realtext","rtf":"application\/x-rtf","rv":"video\/vnd.rn-realvideo","sam":"application\/x-sam","sat":"application\/x-sat","sdp":"application\/sdp","sdw":"application\/x-sdw","sit":"application\/x-stuffit","slb":"application\/x-slb","sld":"application\/x-sld","slk":"drawing\/x-slk","smi":"application\/smil","smil":"application\/smil","smk":"application\/x-smk","snd":"audio\/basic","sol":"text\/plain","sor":"text\/plain","spc":"application\/x-pkcs7-certificates","spl":"application\/futuresplash","spp":"text\/xml","ssm":"application\/streamingmedia","sst":"application\/vnd.ms-pki.certstore","stl":"application\/vnd.ms-pki.stl","stm":"text\/html","sty":"application\/x-sty","svg":"text\/xml","swf":"application\/x-shockwave-flash","tdf":"application\/x-tdf","tg4":"application\/x-tg4","tga":"application\/x-tga","tiff":"image\/tiff","tld":"text\/xml","top":"drawing\/x-top","torrent":"application\/x-bittorrent","tsd":"text\/xml","txt":"text\/plain","uin":"application\/x-icq","uls":"text\/iuls","vcf":"text\/x-vcard","vda":"application\/x-vda","vdx":"application\/vnd.visio","vml":"text\/xml","vpg":"application\/x-vpeg005","vsd":"application\/x-vsd","vss":"application\/vnd.visio","vst":"application\/x-vst","vsw":"application\/vnd.visio","vsx":"application\/vnd.visio","vtx":"application\/vnd.visio","vxml":"text\/xml","wav":"audio\/wav","wax":"audio\/x-ms-wax","wb1":"application\/x-wb1","wb2":"application\/x-wb2","wb3":"application\/x-wb3","wbmp":"image\/vnd.wap.wbmp","wiz":"application\/msword","wk3":"application\/x-wk3","wk4":"application\/x-wk4","wkq":"application\/x-wkq","wks":"application\/x-wks","wm":"video\/x-ms-wm","wma":"audio\/x-ms-wma","wmd":"application\/x-ms-wmd","wmf":"application\/x-wmf","wml":"text\/vnd.wap.wml","wmv":"video\/x-ms-wmv","wmx":"video\/x-ms-wmx","wmz":"application\/x-ms-wmz","wp6":"application\/x-wp6","wpd":"application\/x-wpd","wpg":"application\/x-wpg","wpl":"application\/vnd.ms-wpl","wq1":"application\/x-wq1","wr1":"application\/x-wr1","wri":"application\/x-wri","wrk":"application\/x-wrk","ws":"application\/x-ws","ws2":"application\/x-ws","wsc":"text\/scriptlet","wsdl":"text\/xml","wvx":"video\/x-ms-wvx","xdp":"application\/vnd.adobe.xdp","xdr":"text\/xml","xfd":"application\/vnd.adobe.xfd","xfdf":"application\/vnd.adobe.xfdf","xhtml":"text\/html","xls":"application\/x-xls","xlw":"application\/x-xlw","xml":"text\/xml","xpl":"audio\/scpls","xq":"text\/xml","xql":"text\/xml","xquery":"text\/xml","xsd":"text\/xml","xsl":"text\/xml","xslt":"text\/xml","xwd":"application\/x-xwd","x_b":"application\/x-x_b","sis":"application\/vnd.symbian.install","sisx":"application\/vnd.symbian.install","x_t":"application\/x-x_t","ipa":"application\/vnd.iphone","apk":"application\/vnd.android.package-archive","xap":"application\/x-silverlight-app"};
global.QJHEAD = function(Context){
    Context.headers['Access-Control-Allow-Origin'] = "*";
    Context.headers['Access-Control-Allow-Methods'] = "POST, GET, OPTIONS, DELETE";
    Context.headers['Access-Control-Max-Age'] = "3600";
    Context.headers['Access-Control-Allow-Headers'] = "content-type,x-requested-with,Authorization, x-ui-request,lang";
    Context.headers['Access-Control-Allow-Credentials'] = "true";
    Context.headers["Server"] = 'KuoSoft';
}
global.callback = async (request,context)=> {
    /*request 请求头数据 context 扩展参数*/
    let kuo =   {
        method:"get",
        headers:{},// head 头部
        agent:"",// 浏览器信息
        language:"",//语言
        ip:"127.0.0.1",//用户ip
        host:"",//域名
        path:"",//访问路径
        referer:"",//返回来路
        content :"",//传文件的标示
        body:"",//body 内容
        sessionid:"", //session id
        uid:0,
        class:"",
        func:"",
        func_:"",
        get:{}, //get
        post:{}, //post
        cookie:{}, //cookies
        files:[] //上传文件
    };
    //返回数据
    var Context = {
        statusCode : 200,
        headers:{"content-type":"text/html; charset=UTF-8"},
        body:null
    };
    await new Promise((resolve, reject)=>{

        for(var xx in request.headers){
            request.headers[xx.toLowerCase()] = request.headers[xx];
        }
        kuo.headers = request.headers;
        kuo.agent = request.headers['user-agent'];
        kuo.language = request.headers['accept-language'];
        kuo.host = request.headers.host;
        kuo.referer = request.headers.referer;
        kuo.content = request.headers['content-type'];
        var ip =  request.connection.remoteAddress || request.socket.remoteAddress || request.connection.socket.remoteAddress || '127.0.0.1';
        if(ip && ip.split(',').length>0){
            ip = ip.split(',')[0];
        }
        var urlObj = url.parse(request.url,true,false);
        if(ip){
            kuo.ip   = ip.replace(/::ffff:/g,'');
        }
        kuo.get  = urlObj.query;
        if(urlObj.pathname){
            kuo.path = decodeURI(urlObj.pathname.replace(/\.\./g,''));
        }
        if(kuo.path != "" && kuo.path.slice(0,1) != '/'){
            kuo.path = '/'+kuo.path;
        }
        kuo.method = request.method.toLowerCase();
        if(request.headers.cookie){
            var cookie = request.headers.cookie.split(";");
            for(var ii in cookie){
                if(cookie[ii]){
                    var jixi = cookie[ii].replace(/ /g,'');
                    var jixi_ = jixi.split("=");
                    kuo.cookie[jixi_['0']] = jixi_['1']?jixi_['1']:"";  
                }
            }
        }
        if(!kuo.content){
            kuo.content = "";
        }
        if(kuo.method != "get" ){
            if(kuo.content.indexOf("multipart") > -1){
                try {
                    if( typeof(request.pipe) != "function" || !request.pipe ){
                        if(Http != "tencent"){
                            request.pipe = function(writeStream) {
                                request.on('close', cleanup);
                                request.on('data', onData);
                                request.on('end', onEnd);
                                request.on('error', onEnd);
                                function onData(chunk) {
                                    writeStream.write(chunk);
                                }
                                function onEnd(err) {
                                    if(err){
                                        console.log(err);
                                    }
                                    writeStream.end();
                                }
                                function cleanup() {
                                    request.removeListener('data', onData)
                                    request.removeListener('end', onEnd)
                                    request.removeListener('error', onEnd)
                                    request.removeListener('close', cleanup)
                                }
                            }
                        }else{
                            var body =  Buffer.from(request.body,'base64');
                            request.on = function(xx,vvv){}
                            request.removeListener = function(xx,vvv){};
                            request.pipe = function(writeStream) {
                                writeStream.write(body);
                                writeStream.end();
                            }
                        }
                    }
                    var form = new multiparty.Form({autoFiles: true,uploadDir:temp});
                    form.parse(request, function(err, fields, files) {

                        if(err){
                            if(Debug){
                                p(err);
                            }
                            resolve(kuo);
                            return ;
                        }
                        kuo.files = [];
                        for(var  mz  in  files){
                            var filesfile =files[mz];
                            for(var nn in filesfile){
                                var file = filesfile[nn];
                                if(file.size > 0){
                                    kuo.files.push({
                                        field: file.fieldName,
                                        name: file.originalFilename,
                                        tmp_name: file.path,
                                        size: file.size,
                                    });
                                }
                            } 
                        }

                        if(fields){
                            var post = {};
                            for(var i in fields){
                                if(typeof(fields[i].shift) == "function"){
                                    post[i] = fields[i].shift();
                                }else{
                                    post[i] = fields[i];
                                }
                                _POST_(post,i,post[i]);
                            }
                        
                            kuo.post = post;
                        }
                        resolve(kuo);
                    });
                } catch (error) {
                    if(Debug){
                        p(error);
                    }
                    resolve(kuo);  
                }

            }else{
                if(Http != "tencent"){
                    let postData = '';
                    request.on('data',function(chunk){
                        postData += chunk;
                    });
                    request.on('end' , function(){
                        kuo.body = Buffer.from(postData, 'utf8') ;
                        kuo.post = url.parse("?"+postData,true,false).query;
                        for(var i in kuo.post){
                            if(kuo.post[i].shift){
                                kuo.post[i] = kuo.post[i].shift();
                            }
                            _POST_(kuo.post,i,kuo.post[i]);
                        }
                        resolve(kuo);  
                    });
                    
                }else{
                    var body =  Buffer.from(request.body,'base64');
                    kuo.body = body;
                    kuo.post = url.parse("?"+kuo.body,true,false).query;
                    for(var i in kuo.post){
                        if(kuo.post[i].shift){
                            kuo.post[i] = kuo.post[i].shift();
                        }
                        _POST_(kuo.post,i,kuo.post[i]);
                    }
                    resolve(kuo);
                }
            }
        }
        
        if(kuo.method != "post"){
            resolve(kuo);
        }

    }).then(async function(data){
        Context.headers["Access-Control-Allow-Origin"] = "*";
        if(kuo.get && kuo.get.apptoken && kuo.get.apptoken.length > 63){
            kuo.sessionid = kuo.get.apptoken;
        }else if(kuo.post && kuo.post.apptoken && kuo.post.apptoken.length > 63){
            kuo.sessionid = kuo.post.apptoken;
        }else if( kuo.cookie.apptoken && kuo.cookie.apptoken.length > 63){
            kuo.sessionid = kuo.cookie.apptoken;
        }
        if(kuo.sessionid == "" || kuo.sessionid.length < 63){
            kuo.sessionid = (Mode("Tools").Uuid()+Mode("Tools").Uuid()).replace(/-/g,'')
        }
        let YUANSHI = kuo.path;
        let Path_ = (kuo.path).split("/");
        if(!Path_ || !Path_[0]){
            Path_[0] = "";
        }
        Path_.shift();
        if(Path_ && Path_[0] && ( Path_[0] == "Tpl" || Path_[0] == "attachment" ||  ( WebExt == "" && Path_[0].indexOf(".") > -1) || ( Path_[0].indexOf(".") > -1 && Path_[0].indexOf(WebExt) <= -1 ) ) ){
            Context.headers["Cache-Control"] = "max-age="+(3600*24*30);
            Context.headers["Expires"] = Mode("Tools").SetCookieTiem();
            var houzui = YUANSHI.split(".");
            var houzui_ = houzui.pop().toLowerCase();
            if(Mime[houzui_]){
                Context.headers["content-type"] = Mime[houzui_];
            }else{
                Context.headers["content-type"] = "application/octet-stream";
            }
            try {
                var wenjian = FS.readFileSync(WWW+YUANSHI);
                Context.statusCode = 200;
                Context.body = wenjian ;
            } catch(e) {
                Context.statusCode = 404;
                Context.body = JSON.stringify({code:-1, data:null,msg:"file does not exist : "+YUANSHI,token:""});
            }
            kuo = {};
            return Context;

        }else{

            if(WebExt != ""){
                kuo.path = RTrim(kuo.path,WebExt);
            }
            let Path = (kuo.path).split("/");
            if(kuo.path.indexOf("/admin") <= -1){
                Path = (FENGE+LTrim(kuo.path,'/')).split(FENGE);
            }
            if(!Path || !Path[0]){
                Path[0] = "";
            }
            Path.shift();
            Context.headers["Set-Cookie"] = "apptoken="+kuo.sessionid+";HttpOnly;path=/;expires="+Mode("Tools").SetCookieTiem();
            if(typeof(SecurityGet)== "undefined"){
                global.SecurityGet = ['<', '>', '..', '(', ')', '"', "'", "*", '[', ']', MYSQLconfig.prefix, '{', '}', '$'];
            }
            if(kuo.get){
                var jiexi =  getarray(kuo.get)+"";
                for(var mmm in SecurityGet){
                    if(jiexi.indexOf(SecurityGet[mmm]) > -1){
                        Context.statusCode = 500;
                        Context.body = JSON.stringify({code:-1, data:null,msg:("GET Security: "+SecurityGet[mmm]+" " ),token:""});
                        return Context;
                    }
                }
            }
            if(kuo.post){
                let postSecurity = json_encode(kuo.post)+"";
                if(postSecurity.indexOf(MYSQLconfig.prefix) > -1){
                    Context.statusCode = 500;
                    Context.body = JSON.stringify({code:-1, data:null,msg:("POST Security"),token:""});
                    return Context;
                }
            }
            kuo.class = Defaultclass;
            kuo.func =  Defaultmethod;
            kuo.func_ = Defaultmethod;
            if(!Path[0]){
                Path[0] = "";
                Path[1] = "";
            }
            if( Path[0] != ""){

                if( Defaultplus == "" ){
                    kuo.class = Path[0].toLowerCase();
                    if(Path[1] && Path[1] != ""){
                        kuo.func = Path[1]; 
                        Path.shift();
                    }
                    Path.shift();
                }else{

                    if(Path[0] == Defaultplus){
                        Path.shift();
                        if(Path[0]){
                            kuo.class = Path[0].toLowerCase();
                        }
                        if(Path[1] && Path[1] != ""){
                            kuo.func = Path[1]; 
                            Path.shift();
                        }
                        Path.shift();
                    }else{
                        kuo.func = Path[0];
                        Path.shift();
                    }
                }
            }
            
            if(!global['Kuo_'+kuo.class]){
                try {
                    global['Kuo_'+kuo.class] = require(Controller+'Kuo_'+kuo.class+'.js');
                } catch (ee) {
                    Context.statusCode = 500;
                    Context.body = JSON.stringify({code:-1, data:null,msg:'class error: src/Kuo_'+kuo.class,token:""});
                    return Context;
                }
            }

            if(BLACK[kuo.class] || kuo.class.indexOf('_') > -1){
                Context.statusCode = 500;
                Context.body =  JSON.stringify({code:-1, data:null,msg:"BLACK list: "+kuo.class,token:""});
               
                return Context;
            }
            
            if(!global['Kuo_'+kuo.class]){
                Context.statusCode = 500;
                Context.body = JSON.stringify({code:-1, data:null,msg:("class error: "+kuo.class),token:""});
                return Context;
            }

            if(!global['Kuo_'+kuo.class][kuo.func]){
                kuo.func_ = kuo.func.toLowerCase();
                kuo.func = "Construct";
            }else{
                kuo.func_ =  kuo.func = kuo.func.toLowerCase();
            }

            if(!global['Kuo_'+kuo.class][kuo.func]){
                Context.statusCode = 500;
                Context.body = JSON.stringify({code:-1, data:null,msg:("method error: "+kuo.func),token:""});
                
                return Context;
            }
            kuo.Path = Path;
           
            try {
                await Mode(kuo.class)[kuo.func](kuo,Context,context);
            } catch (error) {
                if(Debug){
                    console.log(error);
                }
                Context.body = JSON.stringify({code:-1, data:null,msg:(error),token:""});; 
            }

            kuo = {};
        }
        
        if(Context.body){
            Context.body = Context.body;
        }else{
            Context.body = "";
        }
        return Context;
       
    }).catch(async (e) => {
        kuo = {};
        Context.body = e.message;;
        Context.statusCode = 500;
        return Context;
    });

    return Context;
}

if(Http == "http"){
    var YSPORT = BIANHAO =  Mode("Tools").Int(BIANHAO);
    if(WSS){
        global.WEBSOCKET = {};
        global.WEBID = 0;
        global.websocket = new WebSocket.Server({ noServer: true });

        function Kuo_NOoP() {}
        function Kuo_BEaT() {
            this.isAlive = true;
        }
        global.WSFindToken = function(token){
            for(var webid in WEBSOCKET){
                let WS = WEBSOCKET[webid];
                if(WS){
                    if(token == WS.TOKEN){
                        delete WEBSOCKET[webid];
                        return WS;
                    }
                }
            }
            return false;
        }

        let Server_ = async () => {
            var Gateway = await Mem.Get("Gateway");
            if(!Gateway ){
                Gateway = {};
            }
            Gateway[YSPORT] = WSUdpIP+":"+(WSUdp+YSPORT);
            await Mem.Set("Gateway",Gateway);
            let Daqu = await db("tanke_area");
            let Daqu_ = await Daqu.Select();
            var houduan = {
                E:"Gateway",
                EB: YSPORT,
                L:WSUdpIP+":"+(WSUdp+YSPORT)
            };
            let SendBuff = MSGPACK.encode(houduan);
            let tongxin = WSUdpServer[0].split(":");
            UDPSERVER.send(SendBuff, 0, SendBuff.length, tongxin[1], tongxin[0]);
            if(Daqu_){
                for(var xx in Daqu_){
                    WSUdpServer[Daqu_[xx].id] = Daqu_[xx].ip;
                    let tongxin = Daqu_[xx].ip.split(":");
                    UDPSERVER.send(SendBuff, 0, SendBuff.length, tongxin[1], tongxin[0]);
                }
            }
            await Mem.Set("UdpServer",WSUdpServer);
        };
        global.UdpSend = function(id,DATA_){
            let shuju = WEBSOCKET[id];
            if(typeof(DATA_)!= "object" || !shuju){
                return "";
            }
            if(DATA_['E']&& DATA_['E'] == 'Online'){
                DATA_["ip"] = shuju.IP;
            }
			DATA_["EE"] = id;
			DATA_["EB"] = BIANHAO;
			DATA_["EU"] = shuju.UID ;
			DATA_["ER"] = shuju.ROLE;
            let Udpip = WSUdpServer[shuju.QHAO];
            if(!Udpip){
                Udpip =  WSUdpServer['0'];
            }
            if(Udpip){
                let tongxin = Udpip.split(":");
                let SendBuff = MSGPACK.encode(DATA_);
                UDPSERVER.send(SendBuff, 0, SendBuff.length, tongxin[1], tongxin[0]);
            }
        }
        if(WSUdpIP != ""){
            Server_();
            UDPSERVER.bind(WSUdp + YSPORT,WSUdpIP);
            UDPSERVER.on('listening', function () {
                console.log('UDP Server '+WSUdpIP+':'+(WSUdp+YSPORT));
            })

            UDPSERVER.on('message', function (msg, rinfo) {
                try {
                    var DATA =  MSGPACK.decode(new Uint8Array(msg));
                } catch (error) {
                    var DATA = null;
                }
                if(DATA){
                    let fid = Mode("Tools").Int(DATA['EE']);
                    if(DATA.E == "SETUP"){
                        //设置用户的信息
                        let D_ = DATA.L;
                        if(WEBSOCKET[fid]){
                            if(D_.U){
                                if(D_.U > 0){
                                    WEBSOCKET[fid].UID = D_.U ;
                                }else if(D_.U < 0){
                                    WEBSOCKET[fid].UID = 0 ;
                                }
                            }
                            if(D_.R){
                                if(D_.R > 0){
                                    WEBSOCKET[fid].ROLE = D_.R ;
                                }else if(D_.R < 0){
                                    WEBSOCKET[fid].ROLE = 0 ;
                                }
                            }
                            if(D_.Q){
                                if(D_.Q > 0){
                                    WEBSOCKET[fid].QHAO = D_.Q ;
                                }else if(D_.Q < 0){
                                    WEBSOCKET[fid].QHAO = 0 ;
                                }
                            }
                        }
                        return ;
                    }
                    let tou = MSGPACK.encode({E:DATA.E,L:DATA.L});
                    if(fid && fid > 0){

                        let shuju = WEBSOCKET[fid];
                        if(shuju){
                            shuju.WS.send(tou);
                        }

                    }else if(fid === 0 ){
                        if(DATA.EF && DATA.EF.length > 0 ){
                            //指定用户通知
                            for(var fid_ in DATA.EF){
                                let webid = DATA.EF[fid_];
                                let WS = WEBSOCKET[webid];
                                if(WS){
                                    WS.WS.send(tou);
                                }
                            }

                        }else{
                             //全服通知
                            for(var webid in WEBSOCKET){
                                let WS = WEBSOCKET[webid];
                                if(WS){
                                    WS.WS.send(tou);
                                }
                            }
                        }

                    }else if(fid < 0){
                        //指定的服全服通知
                        fid = -fid;
                        for(var webid in WEBSOCKET){
                            let WS = WEBSOCKET[webid];
                            if(WS && fid == WS.QHAO  ){
                                WS.WS.send(tou);
                            }
                        }
                    }
                }
            });

            UDPSERVER.on('error', function (err) {
                
            })
        }

        websocket.on('connection', function connection(ws,request) {
            WEBID++;
            ws.isAlive = true;
            //给后台链接通信
            try {
                ws.on('pong', Kuo_BEaT);
                ws.ID = WEBID;
                var ip =  request.connection.remoteAddress || request.socket.remoteAddress || request.connection.socket.remoteAddress || '127.0.0.1';
                if(ip.split(',').length>0){
                    ip = ip.split(',')[0];
                }
                WEBSOCKET[WEBID] = {
                    ID:WEBID,
                    IP:ip.replace(/::ffff:/g,''),
                    UID:0,
                    ROLE:0,
                    QHAO:0,
                    WS:ws,
                    TOKEN:Mode("Tools").Uuid(),
                    LINOFF:1
                }
                ws.on('message', function (message) {
                   
                    if(WEBSOCKET[WEBID].LINOFF == 1){
                        WEBSOCKET[WEBID].LINOFF = 2;
                        setTimeout(() => {
                            if(WEBSOCKET[WEBID].LINOFF != 3){
                                ws.terminate();
                                delete(WEBSOCKET[WEBID]);
                            }
                        }, 1500);
                    }
                    try {
                        var DATA =  MSGPACK.decode(new Uint8Array(message));
                    } catch (error) {
                        var DATA = null;
                    }
                    if(DATA){
                        if( typeof(DATA.Kuo) != "undefined"){
                            WEBSOCKET[WEBID].LINOFF = 3;
                            if(DATA.Kuo != ""){
                                let newtoken = WSFindToken(DATA.Kuo);
                                if(newtoken){
                                    WEBSOCKET[WEBID].UID  = newtoken.UID;
                                    WEBSOCKET[WEBID].ROLE  = newtoken.ROLE;
                                    WEBSOCKET[WEBID].QHAO  = newtoken.QHAO;
                                }
                            }
                            UdpSend(WEBID,{E:'Online'});
                            ws.send(MSGPACK.encode({Kuo:WEBSOCKET[WEBID].TOKEN}));
                            return ;
                        }
                        UdpSend(WEBID,DATA);
                    }
                    
                });
                ws.on('close', function() {
                    //后台发送掉线
                    UdpSend(WEBID,{E:'Dropped'});
                    ws.isAlive = false;
                });

            }catch(error){ }

        });

        setInterval(function () {
            for(var webid in WEBSOCKET){
                let WS = WEBSOCKET[webid];
                if(WS){
                    let ws = WS.WS;
                    if(ws){
                        if (ws.isAlive === false) return ws.terminate();
                        ws.isAlive = false;
                        ws.ping(Kuo_NOoP);
                        ws.send(new Uint8Array());
                    }
                }
            }
        }, WSPingTime);
    }
        
    var httpserver =http.createServer( function(request,response){
        (async () => { 
            try {

                if(HttpPath != ""){
                    request.url = LTrim(request.url ,HttpPath);
                    request.url = LTrim(request.url ,"//");
                }
                var Context = await callback(request);
                Context.headers["content-encoding"] = 'gzip';
                QJHEAD(Context);
                Context.body = ZLIB.gzipSync( Context.body) ;
                response.writeHead(Context.statusCode,Context.headers);
                response.end(Context.body);
            } catch (error) {
                response.end(error);
            }
            
        })();

    });

    if(WSS){
        httpserver.on('upgrade', function upgrade(request, socket, head) {
            const pathname = url.parse(request.url).pathname;

            if (pathname === '/KuoSoft.com') {
                websocket.handleUpgrade(request, socket, head, function done(ws) {
                    websocket.emit('connection', ws, request);
                });
            } else {
                socket.destroy();
            }
        });
        console.log('WS Server 0.0.0.0:'+(httpPort+YSPORT));
    }
    httpserver.listen(httpPort+YSPORT);
    console.log('HTTP Server 0.0.0.0:'+(httpPort+YSPORT));
    if(SSLname != ""){
        const httpsOption = {
            key: FS.readFileSync(dir+"config/"+SSLname+".key"),
            cert: FS.readFileSync(dir+"config/"+SSLname+".pem")
        }
        var httpsserver = https.createServer(httpsOption, function(request,response){
            (async () => { 

                try {
                    if(HttpPath != ""){

                        request.url = LTrim(request.url ,HttpPath);
                        request.url = LTrim(request.url ,"//");
                    }
                    var Context = await callback(request);
                    Context.headers["content-encoding"] = 'gzip';
                    QJHEAD(Context);
                    Context.body = ZLIB.gzipSync(Context.body);
                    response.writeHead(Context.statusCode,Context.headers);
                    response.end(Context.body);
                } catch (error) {
                    response.end(error);
                }

            })();
        });

        if(WSS){
            httpsserver.on('upgrade', function upgrade(request, socket, head) {
                const pathname = url.parse(request.url).pathname;
                if (pathname === '/KuoSoft.com') {
                    websocket.handleUpgrade(request, socket, head, function done(ws) {
                        websocket.emit('connection', ws, request);
                    });
                } else {
                    socket.destroy();
                }
            });
            console.log('WSS Server 0.0.0.0:'+(httpsPort+YSPORT));
        }
        httpsserver.listen(httpsPort+YSPORT);
        console.log('HTTPS Server 0.0.0.0:'+(httpsPort+YSPORT));
    }

   

}else if(Http == "aliyun"){

    exports.handler = async (request, response, context) => {
        
        if(!request.connection){
            request.connection = {remoteAddress:request.clientIP};
        }
        if(HttpPath != ""){
            request.url = LTrim(request.url ,HttpPath);
            request.url = LTrim(request.url ,"//");
        }
        request.url = request.url.replace("2016-08-15","");
        var Context = await callback(request,context);
        response.setStatusCode(Context.statusCode);
        QJHEAD(Context);
        if(Context.headers){
            for(var type in Context.headers){
                response.setHeader(type,Context.headers[type]);
            }
        }
        response.send(Context.body);
    }

}else if(Http == "tencent"){
    exports.main_handler = async (request, context) => {

        if(!request.connection){
            request.connection = {remoteAddress:request.requestContext.sourceIp};
        }
        request.method = request.httpMethod;
        var URLSearchParams = new url.URLSearchParams(request.queryString);
        request.url = (request.path?request.path:"")+"?"+  URLSearchParams.toString();

        if(request.requestContext.path && request.requestContext.path != "" && request.requestContext.path != "/" && request.url){
            request.url = request.url.replace(request.requestContext.path,"");
        }
        if(HttpPath != ""){
            request.url = LTrim(request.url ,HttpPath);
            request.url = LTrim(request.url ,"//");
        }
        var Context = await callback(request,context);
        QJHEAD(Context);
        return {
            "isBase64Encoded": true,
            "statusCode" :Context.statusCode,
            "headers" : Context.headers,
            "body" :  Buffer.from(Context.body).toString('base64') 
        }
        
    };

}else{

    console.log("Call "+Http);
    let Bat_ = Mode(Http);
    if(Bat_ && Bat_.Run){
        var tempx = [];
        var ccc = false;
        for(var ii in  argv){
            if(ccc){
                tempx.push(argv[ii]);
            }else if(argv[ii] == Http){
                ccc = true;
            }
        }
        console.log("Call "+Http+" Run",tempx);
        Bat_.Run(tempx);
    }
}

process.on('SIGINT', function () {
    Mem.Save();
    console.log("exit");
    process.exit();
});